package queues

import (
	"context"
	"encoding/json"
	"fmt"
	"sweetsunnyflower/app/models/user_trip"
	"sweetsunnyflower/pkg/logger"
	"sweetsunnyflower/pkg/queue"
	"sweetsunnyflower/pkg/websocket"
	"time"

	"github.com/hibiken/asynq"
	"github.com/spf13/cast"
)

type TripPayload struct {
	ID uint64
}

const Publish = "publish"

func PublishEvent(ID uint64) {
	payload := TripPayload{
		ID: ID,
	}

	p, _ := json.Marshal(payload)

	queue.NewQueue().Run(asynq.NewTask(Publish, p), 10, time.Second*0)
}

func HandlePublishTask(ctx context.Context, t *asynq.Task) error {
	var p TripPayload
	if err := json.Unmarshal(t.Payload(), &p); err != nil {
		return fmt.Errorf("json.Unmarshal failed: %v: %w", err, asynq.SkipRetry)
	}

	fmt.Println("HandlePublishTask:", p.ID)

	websocketClient := websocket.NewClientManager()
	userTripModel := user_trip.Get(cast.ToString(p.ID))

	userTrip, err := user_trip.FormatTrip(userTripModel)

	if err != nil {
		logger.ErrorString("queues", "HandlePublishTask", err.Error())
		return err
	}

	payload, _ := json.Marshal(userTrip)

	content := websocket.ResponseContent{
		Action:  "new-trip",
		Payload: string(payload),
	}

	cc, _ := json.Marshal(content)

	websocketClient.Broadcast(string(cc), websocket.TextMessage, nil)

	// Email delivery code ...
	return nil
}
